package tcpserver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import tcpserver.config.TcpServerConfig;
import tcpserver.service.TcpServerService;

/**
 * RTU TCP服务器启动类
 * 
 * 基于Spring Boot + Netty的高性能TCP通信服务器
 */
@SpringBootApplication
@EnableConfigurationProperties(TcpServerConfig.class)
public class TcpServerApplication {
    
    private static final Logger logger = LoggerFactory.getLogger(TcpServerApplication.class);
    
    public static void main(String[] args) {
        try {
            logger.info("=================================");
            logger.info("     RTU TCP服务器启动中...     ");
            logger.info("=================================");
            
            // 启动Spring Boot应用
            ConfigurableApplicationContext context = SpringApplication.run(TcpServerApplication.class, args);
            
            // 获取TCP服务器服务
            TcpServerService tcpServerService = context.getBean(TcpServerService.class);
            
            // 添加优雅关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                logger.info("接收到关闭信号，正在优雅关闭服务器...");
                try {
                    context.close();
                    logger.info("服务器已优雅关闭");
                } catch (Exception e) {
                    logger.error("关闭服务器时发生错误", e);
                }
            }));
            
            // 输出启动成功信息
            logger.info("=================================");
            logger.info("     RTU TCP服务器启动完成！    ");
            logger.info("=================================");
            logger.info("TCP服务器状态: {}", tcpServerService.getServerStatus());
            logger.info("Web管理界面: http://localhost:8081");
            logger.info("API文档地址: http://localhost:8081/api/tcp-server/info");
            logger.info("=================================");
            
        } catch (Exception e) {
            logger.error("启动RTU TCP服务器失败", e);
            System.exit(1);
        }
    }
}